<template>
  <el-card>
    <div slot="header" class="clearfix">
      <span>用户管理</span>
      <el-button style="float: right;" type="primary" @click="showAddUserDialog">添加用户</el-button>
    </div>
    <el-table :data="users" style="width: 100%">
      <el-table-column prop="username" label="用户名" width="180"></el-table-column>
      <el-table-column prop="nickname" label="昵称" width="180"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="editUser(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteUser(scope.row.user_id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <el-dialog :visible.sync="dialogVisible" title="用户信息">
    <el-form :model="form">
      <el-form-item label="用户名">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="form.nickname"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveUser">保存</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';

const users = ref([]);
const dialogVisible = ref(false);
const form = ref({
  user_id: null,
  username: '',
  nickname: '',
  email: ''
});

function fetchUsers() {
  axios.get('/api/users').then(response => {
    users.value = response.data;
  });
}

function showAddUserDialog() {
  form.value = { user_id: null, username: '', nickname: '', email: '' };
  dialogVisible.value = true;
}

function editUser(user) {
  form.value = { ...user };
  dialogVisible.value = true;
}

function saveUser() {
  if (form.value.user_id) {
    axios.put(`/api/users/${form.value.user_id}`, form.value).then(() => {
      fetchUsers();
      dialogVisible.value = false;
    });
  } else {
    axios.post('/api/users', form.value).then(() => {
      fetchUsers();
      dialogVisible.value = false;
    });
  }
}

function deleteUser(userId) {
  axios.delete(`/api/users/${userId}`).then(() => {
    fetchUsers();
  });
}

fetchUsers();
</script>

<style scoped>
.el-card {
  margin: 20px;
}
</style> 